<?php

namespace App\Http\Model\Api;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\AudioApi;
use App\Http\Model\Base;
use App\Http\Model\Room;
use App\Http\Model\UserM;
use Exception;

class FinanceCharmStream extends Base
{
    protected $table = 'finance_charm_stream';
    protected $connection = "mysql_kkaudio";

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    public function userRanking($start, $end) {
      $start = strtotime($start);
      $end = strtotime($end);
      return self::with(['user:user_id,uuid,nickname,portrait'])
      ->selectRaw("SUM(charm_value) AS value, user_id")
      ->whereBetween("change_timestamp", [$start, $end])
      ->orderBy("value", "desc")
      ->limit(30)
      ->groupBy("user_id")
      ->get();
    }

    public function roomRanking($start, $end) {
      $start = strtotime($start);
      $end = strtotime($end);
      return self::with(['room:room_id,room_uid,name,image'])
      ->selectRaw("SUM(charm_value) charm_value, room_id")
      ->whereBetween("change_timestamp", [$start, $end])
      ->orderBy("charm_value", "desc")
      ->limit(10)
      ->groupBy("room_id")
      ->get(); 
    }

    public function user() {
      return $this->belongsTo(UserM::class, 'user_id', 'user_id')->withDefault([
        'nickname' => '昵称无',
        'portrait' => '',
        'user_id' => 0,
        'uuid' => '无'
      ]);
    }

    public function room() {
      return $this->belongsTo(Room::class, 'room_id', 'room_id')->withDefault([
        'room_uid' => '昵称无',
        'room_id' => '',
        'name' => '昵称无',
        'image' => ''
      ]);
    }
}